import logging
import os
from typing import Dict, Any
from app.config.settings import settings


class LoggingConfig:
    """日志配置管理类"""
    
    def __init__(self):
        self.log_levels = {
            'DEBUG': logging.DEBUG,
            'INFO': logging.INFO,
            'WARNING': logging.WARNING,
            'ERROR': logging.ERROR,
            'CRITICAL': logging.CRITICAL
        }
    
    def get_log_level(self, level_str: str) -> int:
        """获取日志级别"""
        return self.log_levels.get(level_str.upper(), logging.INFO)
    
    def setup_logging(self):
        """设置全局日志配置"""
        # 启用LangChain详细日志
        os.environ["LANGCHAIN_TRACING_V2"] = "true"
        os.environ["LANGCHAIN_VERBOSE"] = "true"
        os.environ["LANGCHAIN_DEBUG"] = "true"
        
        # 配置根日志记录器
        logging.basicConfig(
            level=self.get_log_level(settings.LOG_LEVEL),
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.StreamHandler(),
                logging.FileHandler('app.log', encoding='utf-8')
            ]
        )
        
        # 配置LangChain相关模块的日志级别
        langchain_level = self.get_log_level(settings.LANGCHAIN_LOG_LEVEL)
        logging.getLogger("langchain").setLevel(langchain_level)
        logging.getLogger("langchain.agents").setLevel(langchain_level)
        logging.getLogger("langchain.llms").setLevel(langchain_level)
        logging.getLogger("langchain.chains").setLevel(langchain_level)
        logging.getLogger("langchain.prompts").setLevel(langchain_level)
        logging.getLogger("langchain.memory").setLevel(langchain_level)
        logging.getLogger("langchain.tools").setLevel(langchain_level)
        
        # 配置大模型相关日志级别
        llm_level = self.get_log_level(settings.LLM_LOG_LEVEL)
        logging.getLogger("app.services.llm").setLevel(llm_level)
        logging.getLogger("app.services.llm.deepseek_service").setLevel(llm_level)
        
        # 配置音频相关日志级别
        audio_level = self.get_log_level(settings.AUDIO_LOG_LEVEL)
        logging.getLogger("app.services.tts").setLevel(audio_level)
        logging.getLogger("app.services.tts.edge_tts_service").setLevel(audio_level)
        
        # 配置其他模块的日志级别
        logging.getLogger("app.services.tools").setLevel(self.get_log_level(settings.LOG_LEVEL))
        logging.getLogger("app.routers").setLevel(self.get_log_level(settings.LOG_LEVEL))
        logging.getLogger("app.utils").setLevel(self.get_log_level(settings.LOG_LEVEL))
    
    def get_logger(self, name: str, module_type: str = "default") -> logging.Logger:
        """获取指定模块的日志记录器
        
        Args:
            name: 日志记录器名称
            module_type: 模块类型 ('audio', 'llm', 'langchain', 'default')
            
        Returns:
            配置好的日志记录器
        """
        logger = logging.getLogger(name)
        
        # 根据模块类型设置日志级别
        if module_type == "audio":
            logger.setLevel(self.get_log_level(settings.AUDIO_LOG_LEVEL))
        elif module_type == "llm":
            logger.setLevel(self.get_log_level(settings.LLM_LOG_LEVEL))
        elif module_type == "langchain":
            logger.setLevel(self.get_log_level(settings.LANGCHAIN_LOG_LEVEL))
        else:
            logger.setLevel(self.get_log_level(settings.LOG_LEVEL))
        
        return logger


# 创建全局日志配置实例
logging_config = LoggingConfig()

# 便捷函数
def get_logger(name: str, module_type: str = "default") -> logging.Logger:
    """获取日志记录器的便捷函数"""
    return logging_config.get_logger(name, module_type)

def setup_logging():
    """设置日志配置的便捷函数"""
    logging_config.setup_logging()